package org.batatasframework.support.database.sql.field;

import java.util.ArrayList;
import java.util.List;

import org.batatasframework.support.database.metadatas.FieldMetadata;
import org.batatasframework.support.database.metadatas.TableMetadata;
import org.batatasframework.support.database.sql.TableRuntimeMaster;
import org.batatasframework.support.database.sql.TableInstance;


/**
 * <pre>处理那些一个查询的结果项需要读取多个数据库表的字段的情况；</pre>
 * @author jackson
 *
 * @param <Field>
 */
public abstract class AbstractMultipleSelectFragment<Field> implements MultipleSelectAppendable{

	protected final List<Field> fields = new ArrayList<>();
	protected final TableRuntimeMaster master;
	protected String title;

	private String[] group;
	
	public AbstractMultipleSelectFragment(TableRuntimeMaster master, String title){
		this.master = master;
		this.title = title;
	}
	
	@Override
	public MultipleSelectAppendable append(TableInstance tableSource, String... fields){
		if(null != fields){
			TableMetadata tableMetadata = tableSource.getTableMetadata();
			for(String field : fields){
				FieldMetadata fieldMetadata = tableMetadata.get(field);
				this.fields.add(_buildField(tableSource, fieldMetadata));
			}
		}
		return this;
	}
	
	public Field buildField(TableInstance tableAlias, FieldMetadata fieldMetadata){
		Field field = _buildField(tableAlias, fieldMetadata);
		this.fields.add(field);
		return field;
	}
	
	protected abstract Field _buildField(TableInstance tableAlias, FieldMetadata fieldMetadata);
	
	@Override
	public String getTitle() {
		return title;
	}
	
	public SelectFragment setTitle(String title) {
		this.title = title;
		return this;
	}

	@Override
	public String[] getGroup() {
		return group;
	}
	
	public SelectFragment setGroup(String[] group) {
		this.group = group;
		return this;
	}
	
	
}
